package com.example.finalproject.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.finalproject.R;
import com.example.finalproject.ui.LoginActivity;
import com.example.finalproject.ui.RegisterActivity;

public class AccountFragment extends Fragment {
    private Button buttonLogin, buttonRegister;
    private TextView text_nickname;
    private Button buttonLogout;
    private TextView textChangeWeatherIcon, textHelp, textFeedback;
    private ViewGroup rootLayout;
    private ImageView wallpaperView;

    public AccountFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_account, container, false);
        rootLayout = root.findViewById(R.id.accountRootLayout);
        buttonLogin = root.findViewById(R.id.button_login);
        buttonRegister = root.findViewById(R.id.button_register);
        text_nickname = root.findViewById(R.id.text_nickname);
        textChangeWeatherIcon = root.findViewById(R.id.textChangeWeatherIcon);
        textHelp = root.findViewById(R.id.textHelp);
        textFeedback = root.findViewById(R.id.textFeedback);
        wallpaperView = root.findViewById(R.id.wallpaperView);

        buttonLogin.setOnClickListener(view -> {
            Intent intentLogin = new Intent(getContext(), LoginActivity.class);
            startActivity(intentLogin);
        });

        buttonRegister.setOnClickListener(view -> {
            Intent intentRegister = new Intent(getContext(), RegisterActivity.class);
            startActivity(intentRegister);
        });

        textChangeWeatherIcon.setOnClickListener(view -> {
            Toast.makeText(getContext(), "功能开发中，敬请期待！", Toast.LENGTH_SHORT).show();
        });

        textHelp.setOnClickListener(view -> {
            Toast.makeText(getContext(), "功能开发中，敬请期待！", Toast.LENGTH_SHORT).show();
        });

        textFeedback.setOnClickListener(view -> {
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            emailIntent.setType("text/plain");
            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "chenkaihan0521@icloud.com" });
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "广工程天气反馈");
            emailIntent.putExtra(Intent.EXTRA_TEXT, "邮件正文");
            startActivity(Intent.createChooser(emailIntent, "选择邮件客户端"));
        });

        handleLogButton(root);
        applyWallpaper();

        return root;
    }

    private void addButtonLogout(View root) {
        buttonLogout = new Button(getContext());
        buttonLogout.setId(View.generateViewId());
        buttonLogout.setText("退出账号");
        buttonLogout.setBackgroundResource(R.drawable.button_bg);
        ConstraintLayout rootLayout = root.findViewById(R.id.accountRootLayout);
        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(
                0, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        lp.startToStart = R.id.guideline3;
        lp.endToStart = R.id.guideline4;
        lp.topToBottom = R.id.text_nickname;
        lp.topMargin = getResources().getDimensionPixelSize(R.dimen.logout_button_margin_top);
        buttonLogout.setLayoutParams(lp);
        rootLayout.addView(buttonLogout);

        buttonLogout.setOnClickListener(view -> {
            SharedPreferences prefs = requireContext().getSharedPreferences("userPrefs", Context.MODE_PRIVATE);
            prefs.edit().remove("loggedInUser").apply();
            onResume();
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        applyWallpaper();  // 每次进入页面时更新壁纸背景
        View root = requireView();
        handleLogButton(root);
    }

    private void handleLogButton(View root) {
        SharedPreferences prefs = requireContext().getSharedPreferences("userPrefs", Context.MODE_PRIVATE);
        String loggedInUser = prefs.getString("loggedInUser", null);
        if (loggedInUser != null) {
            text_nickname.setText(loggedInUser);
            buttonLogin.setVisibility(View.GONE);
            buttonRegister.setVisibility(View.GONE);
            if (buttonLogout == null) {
                addButtonLogout(root);
            }
        } else {
            text_nickname.setText("未登录");
            buttonLogin.setVisibility(View.VISIBLE);
            buttonRegister.setVisibility(View.VISIBLE);
            if (buttonLogout != null) buttonLogout.setVisibility(View.GONE);
        }
    }

    public void applyWallpaper() {
        SharedPreferences prefs = requireContext().getSharedPreferences("weatherPrefs", Context.MODE_PRIVATE);
        String name = prefs.getString("wallpaperName", "wallpaper_forest"); // 默认为wallpaper
        int resId = getResources().getIdentifier(name, "drawable", requireContext().getPackageName());
        wallpaperView.setImageResource(resId);
    }
}